<template>
  <h1>演示地图组件</h1>

  <ul>
    <li>
      <el-button @click="setMarker('刚哥连锁酒店',118.11,25.55)">刚哥连锁酒店</el-button>
      <el-button @click="lx('刚哥连锁酒店',118.11,25.55)">查看驾车路线</el-button>
    </li>
    <li><el-button @click="setMarker('刚哥包子铺',118.11,25.54)">刚哥包子铺</el-button></li>
    <li><el-button @click="setMarker('刚哥槟榔铺',118.11,25.53)">刚哥槟榔铺</el-button></li>
  </ul>

  <div id="map" style=""></div>
</template>

<script setup>
import {onMounted, reactive} from "vue";
let map;
// 当前定位
let point = reactive({lon:0,lat:0})

let setMarker = (name,lon,lat)=>{
  // 清除标注
  map.clearOverlays();
  var point = new BMapGL.Point(lon, lat);
  var marker = new BMapGL.Marker(point);  // 创建标注
  map.addOverlay(marker);              // 将标注添加到地图中
  var opts = {
    width : 200,     // 信息窗口宽度
    height: 10,     // 信息窗口高度
    title : name  // 信息窗口标题
  }
  var infoWindow = new BMapGL.InfoWindow(name, opts);  // 创建信息窗口对象
  // marker.addEventListener("click", function(){
    map.openInfoWindow(infoWindow, point); //开启信息窗口
  // });
}

let lx = (name,lon,lat)=>{
  var output = "长沙到"+name+"驾车需要";
  var searchComplete = function (results){
    if (transit.getStatus() != BMAP_STATUS_SUCCESS){
      return ;
    }
    var plan = results.getPlan(0);
    output += plan.getDuration(true) + "\n";                //获取时间
    output += "总路程为：" ;
    output += plan.getDistance(true) + "\n";             //获取距离
  }
  var transit = new BMapGL.DrivingRoute(map, {renderOptions: {map: map},
    onSearchComplete: searchComplete,
    onPolylinesSet: function(){
      alert(output)
    }});

  var start=new BMapGL.Point(point.lon,point.lat);
  var end=new BMapGL.Point(lon,lat);
  transit.search(start, end);
}

onMounted(()=>{
  map = new BMapGL.Map("map");
  // 开启鼠标缩放
  map.enableScrollWheelZoom();
  // 设置中心点
  map.centerAndZoom("长沙", 12);
  // 添加控件
  var scaleCtrl = new BMapGL.ScaleControl();  // 添加比例尺控件
  map.addControl(scaleCtrl);
  var zoomCtrl = new BMapGL.ZoomControl();  // 添加缩放控件
  map.addControl(zoomCtrl);
  var cityCtrl = new BMapGL.CityListControl();  // 添加城市列表控件
  map.addControl(cityCtrl);

  function myFun(result){
    console.log(result)
    var cityName = result.name;
    map.setCenter(cityName);
    point.lon = result.center.lng;
    point.lat = result.center.lat;
  }
  var myCity = new BMapGL.LocalCity();
  myCity.get(myFun);
})
</script>

<style scoped>
  #map{
    position: fixed !important;
    width: 500px;height: 500px;
    right: 0px;bottom: 50px;
  }
</style>